<template>
  <a-modal
    :visible="visible"
    okText="确定"
    cancelText="取消"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :closable="false"
    width="680px"
    :confirmLoading="confirmLoading"
    @cancel="closeModal()"
    @ok="handleSubmit"
  >
    <a-form-model
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 14 }"
      :model="formData"
      :rules="rules"
      ref="ruleForm"
    >
      <a-form-model-item label="活动名称" prop="name">
        <a-input
          style="width: 300px"
          v-model="formData.name"
          :maxLength="20"
          :disabled="handle == 'view'"
          placeholder="请输入1-20字活动名称"
        />
      </a-form-model-item>
      <a-form-model-item label="开始时间" prop="startTime">
        <a-date-picker
          style="width: 300px"
          v-model="formData.startTime"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD HH:mm:ss"
          show-time
          type="date"
          placeholder="年/月/日 时:分:秒"
          :disabled="formData.isChoose == 1 || handle == 'view'"
          @openChange="handleStartOpenChange"
        />
      </a-form-model-item>
      <a-form-model-item label="结束时间" prop="endTime">
        <a-date-picker
          style="width: 300px"
          v-model="formData.endTime"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD HH:mm:ss"
          show-time
          type="date"
          placeholder="年/月/日 时:分:秒"
          :open="endOpen"
          @openChange="handleEndOpenChange"
          :disabled="handle == 'view'"
        />
      </a-form-model-item>
      <a-form-model-item label="每人限购" prop="purchasing">
        <!-- <a-checkbox style="width: 300px" value="1" v-model="formData.purchasing">开启限购</a-checkbox> -->
        <a-radio-group
          style="width: 300px"
          :options="purchasingList"
          v-model="formData.purchasing"
          :disabled="handle == 'view'"
        ></a-radio-group>
      </a-form-model-item>
      <a-form-model-item
        label="每人每个商品限购"
        v-if="formData.purchasing == 1"
      >
        <a-input-number
          v-model="formData.purchasingCount"
          :precision="0"
          :min="1"
          :max="10000"
          :disabled="handle == 'view'"
        />
        件
      </a-form-model-item>
      <!-- <a-form-model-item label="订单取消" prop="autoCancel">
                买家
                <a-input-number v-model="formData.autoCancel" :precision="0" :min="5" :max="360"/>
                分钟未支付将自动取消订单
                <div class="desc">限制5分钟—360分钟内</div>
            </a-form-model-item> -->
      <a-form-model-item label="是否使用优惠券" prop="useCoupons">
        <a-radio-group
          v-model="formData.useCoupons"
          :options="useCouponsList"
          :disabled="handle == 'view'"
        ></a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="活动预告" prop="activityPreview">
        <a-radio-group
          v-model="formData.activityPreview"
          :options="activityPreviewList"
          :disabled="handle == 'view'"
        ></a-radio-group>
        <div class="desc">用户端该活动下商品是否展示预告时间</div>
      </a-form-model-item>
      <a-form-model-item label="活动标题" prop="title">
        <a-input
          style="width: 300px"
          v-model="formData.title"
          placeholder="未填写则默认为 限时折扣"
          :maxLength="5"
          :disabled="handle == 'view'"
        />
        <div class="desc">2-5个字，活动预告和活动进行期间展示于商品详情页</div>
      </a-form-model-item>
      <a-form-model-item label="活动到期展示" prop="expirationDisplay">
        <a-radio-group
          v-model="formData.expirationDisplay"
          :options="expirationDisplayList"
          :disabled="handle == 'view'"
        ></a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="活动规则" prop="activityRules">
        <div class="rule">
          <a-textarea
            style="width: 300px"
            placeholder="请输入活动规则"
            :auto-size="{ minRows: 3, maxRows: 10 }"
            v-model="formData.activityRules"
            allow-clear
            :maxLength="300"
            :disabled="handle == 'view'"
          />
          <span class="limitWords" v-if="formData.activityRules"
            >{{ formData.activityRules.length || 0 }}/300</span
          >
          <span class="limitWords" v-else>0/300</span>
        </div>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import Moment from "moment";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      //限购列表
      purchasingList: [
        {
          label: "开启",
          value: 1,
        },
        {
          label: "关闭",
          value: 0,
        },
      ],
      //是否使用优惠券
      useCouponsList: [
        {
          label: "否",
          value: 0,
        },
        {
          label: "是",
          value: 1,
        },
      ],
      //活动预告
      activityPreviewList: [
        {
          label: "开启",
          value: 1,
        },
        {
          label: "关闭",
          value: 0,
        },
      ],
      //活动到期展示
      expirationDisplayList: [
        {
          label: "开启",
          value: 1,
        },
        {
          label: "关闭",
          value: 0,
        },
      ],
      endOpen: false,
      formData: {
        name: "", //活动名称
        startTime: "", //开始时间
        endTime: "", //结束时间
        purchasing: 1, //每人限购
        purchasingCount: 1, //每人每个商品限购数量
        autoCancel: 5, //订单取消
        useCoupons: 1, //是否使用优惠券
        activityPreview: 1, //活动预告
        title: "", //活动标题
        expirationDisplay: 1, //活动到期展示
        activityRules: "", //活动规则
        isChoose: false, //是否被微页面选择
      },
      rules: {
        name: [{ required: true, message: "请输入1-20字活动名称" }],
        startTime: [{ required: true, message: "请输入开始时间" }],
        endTime: [
          { required: true, message: "请输入结束时间" },
          {
            validator: (rule, value, callback) => {
              let startTime = new Date(this.formData.startTime).getTime();
              let endTime = new Date(value).getTime();
              if (startTime >= endTime) {
                callback(new Error("活动结束时间不能小于开始时间"));
              } else {
                callback();
              }
            },
          },
        ],
        useCoupons: [{ required: true, message: "请选择是否使用优惠券" }],
        activityPreview: [{ required: true, message: "请选择活动预告" }],
        title: [
          {
            validator: (rule, value, callback) => {
              if (this.formData.title && this.formData.title.length < 2) {
                callback(new Error("请输入2-5个字的活动标题"));
              } else {
                callback();
              }
            },
          },
        ],
        expirationDisplay: [{ required: true, message: "请输入活动到期展示" }],
      },
      confirmLoading: false,
      handle: "edit",
    };
  },
  computed: {
    title() {
      if (this.id) {
        return "编辑活动";
      }
      return "新建活动";
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        if (this.id) {
          this.getInfo(this.id);
        }
      }
    },
  },
  methods: {
    Moment,
    disabledDate(current) {
      return current && current < Moment().add(-1, "days");
    },
    closeModal(freshTable) {
      this.formData = {
        name: "", //活动名称
        startTime: "", //开始时间
        endTime: "", //结束时间
        purchasing: 1, //每人限购
        purchasingCount: 1, //每人每个商品限购数量
        autoCancel: 5, //订单取消
        useCoupons: 1, //是否使用优惠券
        activityPreview: 1, //活动预告
        title: "", //活动标题
        expirationDisplay: 1, //活动到期展示
        activityRules: "", //活动规则
        isChoose: false, //是否被微页面选择
      };
      this.$emit("cancel", freshTable);
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    // 结束时间组件
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    async getInfo(id) {
      let res = await this.$get(
        "goldenhome/seckill/admin_/discount/activity/query",
        { id }
      );
      if (res && res.returnCode == "1000") {
        this.formData = this.apiFieldToCustomField(res.dataInfo);
      }
    },
    //时间转换
    formatDateTime(datetime) {
      let date = new Date(datetime);
      let y = date.getFullYear();
      let m = (date.getMonth() + 1).toString().padStart(2, "0");
      let d = date.getDate().toString().padStart(2, "0");
      let h = date.getHours().toString().padStart(2, "0");
      let i = date.getMinutes().toString().padStart(2, "0");
      let s = date.getSeconds().toString().padStart(2, "0");

      return `${y}-${m}-${d} ${h}:${i}:${s}`;
    },
    //时间比较
    activityStatusCompare(startTime, endTime) {
      let time = new Date().getTime();
      let start = new Date(startTime).getTime();
      let end = new Date(endTime).getTime();
      if (time > start && time < end) {
        return 2; //进行中
      }
      if (time > end && time > start) {
        return 3; //已结束
      }
      return 1; //未开始
    },
    //自定义字段转接口字段
    customFieldToApiField() {
      console.log(
        "formatDateTime",
        this.formatDateTime(this.formData.startTime)
      );
      let activityStatu = this.activityStatusCompare(
        this.formData.startTime,
        this.formData.endTime
      );
      return {
        activityName: this.formData.name, //活动名称
        activityStatu, //秒杀活动状态（1.未开始2.进行中3.已结束）
        activityTitle: this.formData.title,
        startDate: this.formatDateTime(this.formData.startTime), //开始时间
        endDate: this.formatDateTime(this.formData.endTime), //结束时间
        cancelOrderTime: this.formData.autoCancel,
        enableLimit: this.formData.purchasing || 0, //每人限购
        limitCount: this.formData.purchasingCount, //每人每个商品限购数量
        enableExpireShow: this.formData.expirationDisplay, //活动到期展示
        enableCoupon: this.formData.useCoupons, //是否使用优惠券
        enableNotice: this.formData.activityPreview, //活动预告
        remark: this.formData.activityRules, //活动规则
        enableMspage: this.formData.isChoose,
      };
    },
    //接口字段转自定义字段
    apiFieldToCustomField(data) {
      return {
        name: data.activityName, //活动名称
        startTime: data.startDate, //开始时间
        endTime: data.endDate, //结束时间
        purchasing: data.enableLimit, //每人限购
        purchasingCount: data.limitCount || 0, //每人每个商品限购数量
        autoCancel: data.cancelOrderTime, //订单取消
        useCoupons: data.enableCoupon, //是否使用优惠券
        activityPreview: data.enableNotice, //活动预告
        title: data.activityTitle, //活动标题
        expirationDisplay: data.enableExpireShow, //活动到期展示
        activityRules: data.remark, //活动规则
        isChoose: data.enableMspage, //是否被微页面选择
      };
    },
    handleSubmit() {
      this.confirmLoading = true;
      this.$refs.ruleForm.validate((valid) => {
        console.log("valid", valid);
        if (valid) {
          console.log("this.formData", this.formData);
          let data = this.customFieldToApiField();
          let url = "goldenhome/seckill/admin_/discount/activity/add";
          if (this.id) {
            url = "goldenhome/seckill/admin_/discount/activity/update";
            data.id = this.id;
          }
          this.$post(url, data).then((res) => {
            if (res && res.returnCode == "1000") {
              this.$message.success(this.id ? "保存成功" : "添加成功");
              this.confirmLoading = false;
              this.formData = {
                name: "", //活动名称
                startTime: "", //开始时间
                endTime: "", //结束时间
                purchasing: 1, //每人限购
                purchasingCount: 1, //每人每个商品限购数量
                autoCancel: 5, //订单取消
                useCoupons: 1, //是否使用优惠券
                activityPreview: 1, //活动预告
                title: "", //活动标题
                expirationDisplay: 1, //活动到期展示
                activityRules: "", //活动规则
                isChoose: false, //是否被微页面选择
              };
              this.$emit("submit", data);
            }
          });
        } else {
          this.confirmLoading = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.desc {
  color: #ccc;
}
.rule {
  position: relative;
  width: 300px;
  .limitWords {
    position: absolute;
    right: 6px;
    bottom: 4px;
    font-size: 10px;
    color: #ccc;
  }
}
</style>